﻿using SelfMadeMillionaire.Core.Enums;
using SelfMadeMillionaire.Core.Services;
using SelfMadeMillionaire.Core.Specifications.Publications;
using SelfMadeMillionaire.Core.Specifications.Newss;
using SelfMadeMillionaire.Web.Infrastructure.ViewModels.Home;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using SelfMadeMillionaire.Core.Entities;
using System.Web.Configuration;
using System.IO;
using System.Configuration;

namespace SelfMadeMillionaire.Web.Infrastructure.Controllers
{
	public class HomeController : BaseController
	{
		IPublicationService _publicationService;
		ITrackingPortfolioService _trackingPortfolioService;
		INewsletterService _newsletterService;
		ISubscriberService _subscriberService;
        INewsService _newsService;
        IEmailService _emailService;

        public HomeController(IPublicationService publicationService, ITrackingPortfolioService trackingPortfolioService, INewsletterService newsletterService, ISubscriberService subscriberService, INewsService newsService, IEmailService emailService)
		{
			_publicationService = publicationService;
			_trackingPortfolioService = trackingPortfolioService;
			_newsletterService = newsletterService;
			_subscriberService = subscriberService;
            _newsService = newsService;
            _emailService = emailService;
		}

        public ActionResult SmmPromo()
        {
            if (Session["isSessionActive"] == null)
            {
                try
                {
                    int hit_id = 0;
                    LogHit(WebConfigurationManager.ConnectionStrings["DataContext"].ConnectionString,
                                Request.Headers["Referer"] + "",
                                Request.ServerVariables["SCRIPT_NAME"],
                                Request.ServerVariables["REMOTE_ADDR"],
                                Request.ServerVariables["HTTP_USER_AGENT"],
                                Request.Url.AbsoluteUri);
                    Session["isSessionActive"] = 1;
                    //Session[SessionKeys.Hit_ID] = hit_id;
                }
                catch (Exception ex)
                {
                    throw;
                }
            }

            return View();
        }

		
		public ActionResult Index()
		{
            ClearProductTypeInSession();

			var model = new HomeViewModel
			{
				Publications = _publicationService.GetList(new HomePagePublicationsSpecification(GetMinAccessLevel())).ToList()
			};

			return View(model);
		}

        public ActionResult Webinar()
        {
            Session["Subscribe4webinar"] = true;
            return View();
        }

        public ActionResult MarketingLetter(string mailing)
        {
            if (!string.IsNullOrEmpty(mailing))
                _subscriberService.UpdateMODetail_LandingOpen(mailing);

            ViewData["Mailing"] = mailing;
            return View();
        }

        public ActionResult WebinarConfirmation()
        {
            if (Session["Subscribe4webinar"] != null)
            {
                Session["Subscribe4webinar"] = null;
                
                Subscriber subscriber = _subscriberService.Get(User.Identity.Name);
                _emailService.SendWebinarEmail(subscriber);
            }

            ViewBag.Link = WebConfigurationManager.AppSettings["WebinarLink"];
            return View();
        }
        
		[ChildActionOnly]
		public PartialViewResult TrackingPortfolio()
		{
            TrackingPortfolioType trackingPortfolioType;

            switch (GetProductType())
            {
                case ProductType.MaggiesMoneyMountain: trackingPortfolioType = TrackingPortfolioType.MMM; break;
                case ProductType.SelfMadeMillionaire: trackingPortfolioType = TrackingPortfolioType.SMM; break;
                case ProductType.BeginnersPortfolioOptions101: trackingPortfolioType = TrackingPortfolioType.Beginners; break;
                default: trackingPortfolioType = TrackingPortfolioType.SMM; break;
            }
			var model = _trackingPortfolioService.Get(trackingPortfolioType);
			return PartialView("AnnualizedControl", model);
		}

		[ChildActionOnly]
		public PartialViewResult TrackingPortfolioPerfomance()
		{
			var model = _newsletterService.GetList(new TrackingPortfolioPerfomanceSpecification(1, GetProductType().HasValue ? GetProductType().Value : ProductType.SelfMadeMillionaire, GetMinAccessLevel())).FirstOrDefault();
			return PartialView(model);
		}

		[ChildActionOnly]
		public PartialViewResult RecentIssues()
		{
            ProductType? productType = GetProductType();
            ViewData["SelectedProduct"] = productType.HasValue ? (int)productType.Value : (int)ProductType.SelfMadeMillionaire;

            List<Newsletter> m = new List<Newsletter>();
            if (!productType.HasValue)
            {
                var mmm = _newsletterService.GetMmmRecentIssues().ToList();
                foreach (var i in mmm)
                {
                    m.Insert(0, i);
                }

                productType = ProductType.SelfMadeMillionaire;
            }

            if (productType == ProductType.MaggiesMoneyMountain)
            {
                m.AddRange(_newsletterService.GetList(new RecentIssuesSpecification(4, ProductType.MaggiesMoneyMountain, SubscriptionType.Platinum)));
            }
            else
            {
                m.AddRange(_newsletterService.GetList(new RecentIssuesSpecification(4, productType.Value, GetMinAccessLevel())).ToList());
            }

            m = m.OrderByDescending(i => i.Date).ToList();
            return PartialView(m);
		}

		[ChildActionOnly]
		public PartialViewResult Publications()
		{
            PublicationNewsListViewModel model = new PublicationNewsListViewModel();
            model.SelectedProduct = GetProductType().HasValue ? GetProductType().Value : ProductType.SelfMadeMillionaire;
            model.Publications = _publicationService.GetList(new RecentPublicationsSpecification(4, model.SelectedProduct, GetMinAccessLevel())).ToList();
            model.News = _newsService.GetList(new RecentNewsSpecification(2, model.SelectedProduct, GetMinAccessLevel())).ToList();
            model.CreateMixedList();
            
            return PartialView(model);
		}

        [ChildActionOnly]
        public PartialViewResult Education()
        {
            ViewData["SelectedProduct"] = (int)(GetProductType().HasValue ? GetProductType().Value : ProductType.SelfMadeMillionaire);
            var model = _publicationService.GetList(new EducationPublicationsSpecification(4, GetProductType().HasValue ? GetProductType().Value : ProductType.SelfMadeMillionaire, GetMinAccessLevel())).ToList();
            return PartialView(model);
        }

		private SubscriptionType GetMinAccessLevel()
		{
			var minAccessLevel = SubscriptionType.Free;
			if (Request.IsAuthenticated)
				minAccessLevel = _subscriberService.GetMinAccessLevel(User.Identity.Name);

			return minAccessLevel;
		}

        [ChildActionOnly]
        public ActionResult RenewText()
        {
            Subscriber subscriber = _subscriberService.Get(User.Identity.Name);
            if (subscriber.IsPlatinumSubscriber())
                return Content("<br />Renew My Subscription<br />");
            return Content("Upgrade My<br />Subscription<br />Risk FREE");
        }

        /*public FilePathResult GetMailingImage(string mailing)
        {
            if (!string.IsNullOrEmpty(mailing))
                _mailingOpenLogService.Add(mailing);

            string path = ConfigurationManager.AppSettings["MailingImage"];
            
            string mimeType = "image/jpeg";
            string ext = Path.GetExtension(path).Substring(1);
            if (ext.ToLower() == "png")
                mimeType = "image/png";
            else if (ext.ToLower() == "gif")
                mimeType = "image/gif";
            else if (ext.ToLower() == "bmp")
                mimeType = "image/bmp";

            return File(path, mimeType);
        }*/
	}
}
